package com.auxgroup.smarthome.inner.repo;

import com.auxgroup.smarthome.inner.entity.AppPushTemplateEntity;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by niuGuangzhe on 2017/8/8.
 */
public class AppPushTemplateRepoSpec {
    /**
     * @param keyword       关键字
     * @param pushTimeStart 搜索开始时间
     * @param pushTimeEnd   搜索结束时间
     * @param progress      已经保存|已经发送
     * @return
     */
    public static Specification<AppPushTemplateEntity> findByUncertainParameters(final String keyword,
                                                                                 final Date pushTimeStart,
                                                                                 final Date pushTimeEnd,
                                                                                 final Integer progress) {
        return new Specification<AppPushTemplateEntity>() {
            @Override
            public Predicate toPredicate(Root<AppPushTemplateEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                if (keyword != null && !"".equals(keyword)) {
                    Predicate one=criteriaBuilder.like(root.<String>get("templateTitle"), "%" + keyword + "%");
                    Predicate two=criteriaBuilder.like(root.<String>get("templateContent"), "%" + keyword + "%");
                    predicates.add(criteriaBuilder.or(one,two));
                }
                if (progress != null && progress >= 0) {
                    predicates.add(criteriaBuilder.equal(root.<Integer>get("status"), progress));
                } else {
                    //如果什么都没有，就自动包括0和1,即保存以及发布
                    predicates.add(criteriaBuilder.notEqual(root.get("status"), 2));
                }
                if (pushTimeStart != null) {
                    predicates.add(criteriaBuilder.greaterThan(root.<Date>get("pushTime"), pushTimeStart));
                }
                if (pushTimeEnd != null) {
                    predicates.add(criteriaBuilder.lessThan(root.<Date>get("pushTime"), pushTimeEnd));
                }

                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };

    }
}
